<?php

namespace App\Imports;

use App\Models\Car;
use App\Models\Config;
use Maatwebsite\Excel\Concerns\ToModel;

class CarImport implements  ToModel
{
    private $num = 0;
    private $date;

    public function getCsvSettings(): array
    {
        return [
            'input_encoding' => 'utf-8'
        ];
    }

    public function model(array $row)
    {
        if ($this->num == 0) {
            list($year, $other) = explode("年", $row[0]);
            list($month, $day) = explode("月", $other);
            $day = rtrim($day, '日');
            $date = $year . "-" . $month . "-" . $day;
            $this->date = date('Y-m-d', strtotime($date));
            if (!$this->date) {
                throw new \Exception("请检查第一行日期格式是不是如: 2011年11月11日 类似格式");
            } else {
                $exist = Car::where('is_publish', 0)->exists();
                if ($exist) {
                    throw new \Exception("存在未发布的数据，请先发布");
                }
//                $history_date = Car::orderBy('id', 'desc')->value('date');
//                if ($history_date && strtotime($history_date) > time()) {
//                    $history_date = date('Y-m-d', strtotime($history_date));
//                    if ($history_date != $this->date) {
//                        Car::where('date', ">=", date('Y-m-d'))->delete();
//                    }
//                }
            }
//            $start = Config::getTime()['start'];
//            $this->date .=  " " . $start;
        }
        if ($this->num >= 3) {
            if ($row[1] != '' || $row[2] != '') {
                Car::create([
                    'carrier_unit' => $row[1],
                    'car_num' => $row[2],
                    'trailer_num' => $row[3],
                    'weight' => $row[4],
                    'is_cold' => $row[5] ?? '否',
                    'driver' => $row[6],
                    'supercargo' => $row[7],
                    'delivery_unit' => $row[8],
//                    'date' => $this->date,
                    'cur_date' => $this->date
                ]);
            }
        }
        $this->num = $this->num + 1;
    }

}
